package com.znsb.msfq.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.baidu.mobstat.StatService;
import com.znsb.msfq.BaseFragment;
import com.znsb.msfq.R;
import com.znsb.msfq.activity.CommodityDetailsActivity;
import com.znsb.msfq.activity.MainActivity;
import com.znsb.msfq.activity.WebViewActivity;
import com.znsb.msfq.adapter.comadapter.CommonAdapter;
import com.znsb.msfq.adapter.comadapter.ViewHolder;
import com.znsb.msfq.app.ZnsbApp;
import com.znsb.msfq.bean.H1ShopItemBean;
import com.znsb.msfq.bean.H1genreItemBean;
import com.znsb.msfq.broadcast.ListenerManager;
import com.znsb.msfq.dialog.UpAppDialog;
import com.znsb.msfq.utils.ActivityUtil;
import com.znsb.msfq.utils.DeviceUtils;
import com.znsb.msfq.utils.GsonUtils;
import com.znsb.msfq.utils.HttpUtils;
import com.znsb.msfq.utils.ImageLoader;
import com.znsb.msfq.utils.JsonResult;
import com.znsb.msfq.utils.LogUtils;
import com.znsb.msfq.utils.NetworkAddress;
import com.znsb.msfq.utils.OverallData;
import com.znsb.msfq.utils.ResponseUtils;
import com.znsb.msfq.utils.StringUtils;
import com.znsb.msfq.view.NoScrollGridView;
import com.znsb.msfq.view.NoScrollListView;
import com.znsb.msfq.view.bgabanner.BGABanner;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * 名称：首页
 * 创建时间：2016/10/20.
 * 作者：杨广
 * 手机号：13330359437
 * 说明：
 */

public class Home1Fragment extends BaseFragment {


    @Bind(R.id.h1f_hgv_gridview)
    NoScrollGridView h1fHgvGridview;
    @Bind(R.id.h1f_listview)
    NoScrollListView h1fListview;
    @Bind(R.id.mhp_banner)
    BGABanner mBanner;
    @Bind(R.id.h1_list_swiperefresh_layout)
    SwipeRefreshLayout listSwiperefreshLayout;
    private MainActivity activity;
    //    Banner
    private ArrayList<ArrayList<String>> banners;
    private ArrayList<ArrayList<String>> bannersurl;
    private ArrayList<ArrayList<String>> type;
    private ArrayList<ArrayList<Integer>> goodsId;
    private List<H1genreItemBean> list;
    private List<H1ShopItemBean> dataItems;

    public void setActivity(MainActivity activity) {
        this.activity = activity;
    }

    @Override
    protected int getlayoutView() {
        return R.layout.frag_home1;
    }

    @Override
    protected void initView(View view) {
    }

    @Override
    protected void initData() {
        /**
         * 列表属性配置
         */
        listSwiperefreshLayout.setColorSchemeResources(R.color.blueStatus);
        listSwiperefreshLayout.setOnRefreshListener(onRefresh);
        banners = new ArrayList<>();
        bannersurl = new ArrayList<>();
        type = new ArrayList<>();
        goodsId = new ArrayList<>();
        list = new ArrayList<>();
        dataItems = new ArrayList<H1ShopItemBean>();
        GetBanner();
    }

    private Handler hander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 300:
                    setHeaderBanners(banners.get(0), bannersurl.get(0));
                    SetCategorysList();
                    SetList();
                    break;
                case 0:
                    new UpAppDialog(getActivity(), "您有新的版本更新，请去市场更新");
                    break;


            }

        }
    };

    /**
     * 下拉刷新
     */
    private SwipeRefreshLayout.OnRefreshListener onRefresh = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    banners.clear();
                    bannersurl.clear();
                    type.clear();
                    goodsId.clear();
                    list.clear();
                    dataItems.clear();
                    GetBanner();
                    listSwiperefreshLayout.setRefreshing(false);
                }
            }, 1000);
        }
    };

    public void setHeaderBanners(final List<String> bannerimg, final List<String> imgweburls) {
        if (bannerimg.size() < 1) {
            return;
        }
        mBanner.setData(bannerimg, null);
        mBanner.setAdapter(new BGABanner.Adapter() {
            @Override
            public void fillBannerItem(BGABanner banner, View view, Object model, int position) {
                ImageLoader.imageLoderNo((ImageView) view, "" + bannerimg.get(position));
            }
        });
        mBanner.setOnItemClickListener(new BGABanner.OnItemClickListener() {
            @Override
            public void onBannerItemClick(BGABanner bgaBanner, View view, Object o, int i) {
                int index = mBanner.getCurrentItem();
                Bundle bundle = new Bundle();
                if (type.size() > 0) {
                    if (type.get(0).size() > index) {
                        if (type.get(0).get(index).equals("1")) {//banner类型，0内部链接，1外部链接
                            if (imgweburls.size() > index) {
                                bundle.putString("url", imgweburls.get(index));
                                ActivityUtil.next(getActivity(), WebViewActivity.class, bundle);
                            }
                        } else {
                            if (goodsId.size() > 0) {
                                if (goodsId.get(0).size() > index) {
                                    bundle.putInt("ids", goodsId.get(0).get(index));
                                    ActivityUtil.next(getActivity(), CommodityDetailsActivity.class, bundle);
                                }
                            }

                        }
                    }

                }

            }
        });
    }

    public void SetCategorysList() {
        if (list.size() < 1) {
            return;
        }
        h1fHgvGridview.setAdapter(new CommonAdapter<H1genreItemBean>(getActivity(), R.layout.item_home1_shoptype, list) {

            @Override
            protected void fillItemData(ViewHolder viewHolder, int position,
                                        H1genreItemBean item) {
                // 设置图片
                viewHolder.setImageByUrl(R.id.iht_iv_typepic, item.logo);
                //设置texts
                viewHolder.setText(R.id.iht_iv_typename, item.title);

            }

        });
        h1fHgvGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //发送广播通知所有注册该接口的监听器
                ListenerManager.getInstance().sendBroadCast(list.get(position).getId());
                OverallData.setIndex(list.get(position).getId());
                activity.setTabSelection();
            }
        });
    }

    private void SetList() {

        h1fListview.setAdapter(new CommonAdapter<H1ShopItemBean>(getActivity(), R.layout.item_home1_shop, dataItems) {

            @Override
            protected void fillItemData(ViewHolder viewHolder, final int position,
                                        H1ShopItemBean item) {
                final int index = position;
                final int indexs = position + 1;
                final H1ShopItemBean items = item;
                // 设置图片
                viewHolder.setImageByUrl(R.id.ihs_iv_shop1img, item.h1shop1img,index);
                viewHolder.setImageByUrlround(R.id.ihs_iv_shop1imgly, item.h1shop1imgly,index);
                viewHolder.setImageByUrl(R.id.ihs_iv_shop2img, item.h1shop2img,index);
                viewHolder.setImageByUrlround(R.id.ihs_iv_shop2imgly, item.h1shop2imgly,index);
                viewHolder.setImageByUrl(R.id.ihs_iv_shop3img, item.h1shop3img,index);
                viewHolder.setImageByUrlround(R.id.ihs_iv_shop3imgly, item.h1shop3imgly,index);
                viewHolder.setImageByUrl(R.id.ihs_iv_shop4img, item.h1shop4img,index);
                viewHolder.setImageByUrlround(R.id.ihs_iv_shop4imgly, item.h1shop4imgly,index);
                viewHolder.setImageByUrl(R.id.ihs_iv_shop5img, item.h1shop5img,index);
                viewHolder.setImageByUrlround(R.id.ihs_iv_shop5imgly, item.h1shop5imgly,index);
                viewHolder.setImageByUrl(R.id.ihs_iv_shopimg, item.h1shopimg,index);
                // 设置text
                viewHolder.setText(R.id.ihs_tv_typesname, item.h1shoptypename);
                viewHolder.setText(R.id.ihs_tv_shop1name, item.h1shop1name);
                viewHolder.setText(R.id.ihs_tv_shop1state, item.h1shop1state);
                viewHolder.setText(R.id.ihs_tv_shop1pice, item.h1shop1cost);
                viewHolder.setText(R.id.ihs_tv_shop2name, item.h1shop2name);
                viewHolder.setText(R.id.ihs_tv_shop2pice, item.h1shop2cost);
                viewHolder.setText(R.id.ihs_tv_shop3name, item.h1shop3name);
                viewHolder.setText(R.id.ihs_tv_shop3pice, item.h1shop3cost);
                viewHolder.setText(R.id.ihs_tv_shop4name, item.h1shop4name);
                viewHolder.setText(R.id.ihs_tv_shop4pice, item.h1shop4cost);
                viewHolder.setText(R.id.ihs_tv_shop5name, item.h1shop5name);
                viewHolder.setText(R.id.ihs_tv_shop5pice, item.h1shop5cost);
                viewHolder.setOnClickListener(R.id.ihs_tv_typemore, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        OverallData.setIndex(dataItems.get(position).categoryId);
                        //发送广播通知所有注册该接口的监听器
                        ListenerManager.getInstance().sendBroadCast(dataItems.get(position).categoryId);
                        activity.setTabSelection();
                    }
                });
                viewHolder.setOnClickListener(R.id.ihs_ll_shop1, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id=items.h1id;
                        if (id!=-100){
                            Bundle bundle = new Bundle();
                            bundle.putInt("ids", id);
                            ActivityUtil.next(getActivity(), CommodityDetailsActivity.class, bundle);
                        }
                    }
                });
                viewHolder.setOnClickListener(R.id.ihs_ll_shop2, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id=items.h2id;
                        if (id!=-100){
                            Bundle bundle = new Bundle();
                            bundle.putInt("ids", id);
                            ActivityUtil.next(getActivity(), CommodityDetailsActivity.class, bundle);
                        }
                    }
                });
                viewHolder.setOnClickListener(R.id.ihs_ll_shop3, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id=items.h3id;
                        if (id!=-100){
                            Bundle bundle = new Bundle();
                            bundle.putInt("ids", id);
                            ActivityUtil.next(getActivity(), CommodityDetailsActivity.class, bundle);
                        }
                    }
                });
                viewHolder.setOnClickListener(R.id.ihs_ll_shop4, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id=items.h4id;
                        if (id!=-100){
                            Bundle bundle = new Bundle();
                            bundle.putInt("ids", id);
                            ActivityUtil.next(getActivity(), CommodityDetailsActivity.class, bundle);
                        }
                    }
                });
                viewHolder.setOnClickListener(R.id.ihs_ll_shop5, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id=items.h5id;
                        if (id!=-100){
                            Bundle bundle = new Bundle();
                            bundle.putInt("ids", id);
                            ActivityUtil.next(getActivity(), CommodityDetailsActivity.class, bundle);
                        }

                    }
                });
                viewHolder.setOnClickListener(R.id.ihs_iv_shopimg, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        {
                            Bundle bundle = new Bundle();

                            if (type.size() > indexs) {
                                if (type.get(indexs).size() > 0) {
                                    if (type.get(indexs).get(0).equals("1")) {//banner类型，0内部链接，1外部链接
                                        String url = bannersurl.get(indexs).get(0);
                                        if (StringUtils.isNotNull(url)) {
                                            bundle.putString("url", url);
                                            ActivityUtil.next(getActivity(), WebViewActivity.class, bundle);
                                        }

                                    }
                                } else {
                                    if (goodsId.size() > indexs) {
                                        if (goodsId.get(indexs).size() > 0) {
                                            bundle.putInt("ids", goodsId.get(indexs).get(0));
                                            ActivityUtil.next(getActivity(), CommodityDetailsActivity.class, bundle);
                                        }
                                    }

                                }

                            }

                        }
                    }
                });


            }

        });


    }


    //获取banner数据
    void GetBanner() {
        Map<String, Object> maps = new HashMap<>();
        maps.put("size", 6);
        maps.put("post", 0);
        HttpUtils.getInstance(getActivity()).postAsnyRequest(NetworkAddress.Banner, HttpUtils.getMaps(maps), new ResponseUtils() {
            @Override
            public void onSucceed(String code, JSONObject request) {
                try {
                    LogUtils.i("", ">>>>>>GetBanner" + request);

                    JSONArray dataList = JsonResult.getJSONArray(request, "dataList");
                    for (int i = 0; i < dataList.length(); i++) {
                        ArrayList<String> banner = new ArrayList<>();
                        ArrayList<String> bannersurls = new ArrayList<>();
                        ArrayList<String> typelist = new ArrayList<>();
                        ArrayList<Integer> goodsIdlist = new ArrayList<>();
                        JSONObject jsonObject = dataList.getJSONObject(i);
                        JSONArray dataLists = JsonResult.getJSONArray(jsonObject, "dataList");
                        for (int j = 0; j < dataLists.length(); j++) {
                            JSONObject jsonObjects = dataLists.getJSONObject(j);
                            String url = JsonResult.getString(jsonObjects, "url");
                            String link = JsonResult.getString(jsonObjects, "link");
                            String types = JsonResult.getString(jsonObjects, "type");
                            int goodsIds = JsonResult.getInt(jsonObjects, "goodsId");
                            banner.add(url);
                            bannersurls.add(link);
                            typelist.add(types);
                            goodsIdlist.add(goodsIds);
                        }
                        type.add(typelist);
                        goodsId.add(goodsIdlist);
                        banners.add(i, banner);
                        bannersurl.add(i, bannersurls);
                    }

                } catch (Exception e) {
                    LogUtils.i("", ">>>>>>e" + e);
                }
                GetCategorys();
                GetRecommendGoods();
            }

            @Override
            public void onFailure(String result) {
                LogUtils.i("", ">>>>>>onFailure" + result);
            }
        });


    }

    //商品分类列表
    public void GetCategorys() {

        Map<String, Object> maps = new HashMap<>();
        maps.put("isRecommend", 1);//是否推荐分类，0不推荐，1推荐，不传默认不推荐
        maps.put("pageSize", 10);//一页多少条，不传递默认10条
        HttpUtils.getInstance(getActivity()).postAsnyRequest(NetworkAddress.Categorys, HttpUtils.getMaps(maps), new ResponseUtils() {
            @Override
            public void onSucceed(String code, JSONObject request) {
                try {
                    LogUtils.i("", ">>>>>>GetCategorys" + request);
                    JSONArray dataList = JsonResult.getJSONArray(request, "dataList");
                    for (int i = 0; i < dataList.length(); i++) {
                        JSONObject jsonObject = dataList.getJSONObject(i);
                        try {
                            H1genreItemBean h1genreItemBean = (H1genreItemBean) GsonUtils.getGsonData(H1genreItemBean.class, jsonObject.toString());
                            list.add(h1genreItemBean);
                        } catch (Exception e) {
                            LogUtils.i("", ">>>>>>e" + e);
                        }
                    }
                } catch (Exception e) {
                    LogUtils.i("", ">>>>>>e" + e);
                }
            }

            @Override
            public void onFailure(String result) {
                LogUtils.i("", ">>>>>>onFailure" + result);
            }
        });
    }


    //推荐商品
    void GetRecommendGoods() {

        Map<String, Object> maps = new HashMap<>();
        HttpUtils.getInstance(getActivity()).postAsnyRequest(NetworkAddress.RecommendGoods, HttpUtils.getMaps(null), new ResponseUtils() {
            @Override
            public void onSucceed(String code, JSONObject request) {
                try {
                    LogUtils.i("", ">>>>>>RecommendGoods" + request);

                    JSONArray dataList = JsonResult.getJSONArray(request, "dataList");
                    for (int i = 0; i < dataList.length(); i++) {
                        JSONObject jsonObject = dataList.getJSONObject(i);
                        int categoryId = JsonResult.getInt(jsonObject, "categoryId");
                        String categoryName = JsonResult.getString(jsonObject, "categoryName");
                        JSONArray dataLists = JsonResult.getJSONArray(jsonObject, "dataList");
                        if (dataLists.length() > 0 && banners.size() > 1) {
                            String img = "";
                            try {
                                img = banners.get(i + 1).get(0);
                            } catch (Exception e) {
                            }
                            dataItems.add(new H1ShopItemBean(categoryId, categoryName, JsonResult.getInt(JsonResult.getJSONArray(dataLists, 0), "id"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 0), "title"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 0), "introduction"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 0), "售价：¥", "price"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 0), "logo"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 0), "sourceLogo"), JsonResult.getInt(JsonResult.getJSONArray(dataLists, 1), "id"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 1), "title"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 1), "售价：¥", "price"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 1), "logo"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 1), "sourceLogo"), JsonResult.getInt(JsonResult.getJSONArray(dataLists, 2), "id"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 2), "title"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 2), "售价：¥", "price"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 2), "logo"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 2), "sourceLogo"), JsonResult.getInt(JsonResult.getJSONArray(dataLists, 3), "id"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 3), "title"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 3), "售价：¥", "price"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 3), "logo"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 3), "sourceLogo"), JsonResult.getInt(JsonResult.getJSONArray(dataLists, 4), "id"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 4), "title"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 4), "售价：¥", "price"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 4), "logo"), JsonResult.getString(JsonResult.getJSONArray(dataLists, 4), "sourceLogo"), img));
                        }

                    }
                } catch (Exception e) {
                    LogUtils.i("", ">>>>>>e" + e);
                }
                hander.sendEmptyMessage(300);

            }

            @Override
            public void onFailure(String result) {
                LogUtils.i("", ">>>>>>onFailure" + result);
            }
        });

    }


    @Override
    protected void clickListener(View view) {

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate recyler_divider fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onResume() {
        super.onResume();
        // 页面埋点
        StatService.onPageStart(getActivity(), "首页");
    }

    @Override
    public void onPause() {
        super.onPause();
        // 页面埋点
        StatService.onPageEnd(getActivity(), "首页");
    }


}